//
//  LoginViewController.m
//  League
//
//  Created by 博宇 李 on 2018/1/22.
//  Copyright © 2018年 ciyuanjuzhen. All rights reserved.
//

#import "LoginViewController.h"
#import "FirstViewController.h"
#import "LoginTextFiledView.h"
#import "RegisterViewController.h"
#import "InternationalControl.h"
#import "PGGDropView.h"
#import "LoginModel.h"
#import "UserInfomation.h"
#import "OCRegisterViewController.h"

#define kTextFiledBgColor [UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1]
@interface LoginViewController ()<PGGDropDelegate>
{
    NSBundle *bundle;
    NSInteger selectNumIndex;
    NSArray *counterNum;
}
@property(strong,nonatomic)PGGDropView * dropView;
@property(strong , nonatomic)LoginTextFiledView *loginView;
@end

@implementation LoginViewController

-(void)viewDidDisappear:(BOOL)animated
{
     [[NSNotificationCenter defaultCenter] removeObserver:self name:kChangeLoginNotificationName object:nil];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"";
    selectNumIndex = 0;
    counterNum = [NSArray arrayWithObjects:@"+86",@"+852", nil];
    [self setupLoginView];
    
    NSString *lan = [InternationalControl userLanguage];
    
    if([lan isEqualToString:@"en"]){//判断当前的语言，进行改变
        
        [self.loginView.changLau setTitle:@"中文" forState:UIControlStateNormal];
        
    }else{
        [self.loginView.changLau setTitle:@"English" forState:UIControlStateNormal];
        
    }
    [self changLau];
    
//    UIButton *testBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 20, 100, 100)];
//    testBtn.backgroundColor = [UIColor redColor];
//    [testBtn addTarget:self action:@selector(test:) forControlEvents:UIControlEventTouchDown];
//    [self.view addSubview:testBtn];
    
    // Do any additional setup after loading the view.
    
    
    //是否自动登录
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if([[defaults stringForKey:kIsLogin] isEqualToString:kLoginStr]){
        if(![defaults objectForKey:kUserName] || ![defaults objectForKey:kUserPassWord]){
            return;
        }
        self.loginView.userNameTf.text = [defaults objectForKey:kUserName];
        self.loginView.userPassWordTf.text = [defaults objectForKey:kUserPassWord];
        self.loginView.remberPwImage.selected = YES;
//        [self loginBtn:nil];
    }
}
- (void)setupLoginView
{
    self.loginView = [[LoginTextFiledView alloc ] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    [self.loginView.loginBtn addTarget:self action:@selector(loginBtn:) forControlEvents:UIControlEventTouchDown];
    [self.loginView.registerBtn addTarget:self action:@selector(registerBtn:) forControlEvents:UIControlEventTouchDown];
    [self.loginView.changLau addTarget:self action:@selector(chang:) forControlEvents:UIControlEventTouchDown];
    [self.loginView.forgetPWBtn addTarget:self action:@selector(forget:) forControlEvents:UIControlEventTouchDown];
    [self.loginView.remberPwImage addTarget:self action:@selector(rember:) forControlEvents:UIControlEventTouchDown];
     [self.loginView.countryNumberBtn addTarget:self action:@selector(counterNum:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:self.loginView];
    [self.loginView.countryNumberBtn setTitle:counterNum[selectNumIndex] forState:UIControlStateNormal];
}


-(void)counterNum:(UIButton *)btn
{
    /*
    [self.dropView removeFromSuperview];
    self.dropView = [[PGGDropView alloc] initWithFrame:CGRectMake(0, 0 ,self.view.width, 100) withTitleArray:counterNum];
    self.dropView.center = CGPointMake(self.view.width/2, self.view.height/2);
    self.dropView.backgroundColor = kTextFiledBgColor;
    [self.dropView beginAnimation];
    self.dropView.delegate = self;
    [self.view addSubview:self.dropView];
     */
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
        
    }];
    UIAlertAction *walkingBtn = [UIAlertAction actionWithTitle:@"+86" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        selectNumIndex = 0;
        [self.loginView.countryNumberBtn setTitle:counterNum[selectNumIndex] forState:UIControlStateNormal];
    }];
    UIAlertAction *gaodeNavigation = [UIAlertAction actionWithTitle:@"+852" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        selectNumIndex = 1;
        [self.loginView.countryNumberBtn setTitle:counterNum[selectNumIndex] forState:UIControlStateNormal];
    }];
    
    [alertVc addAction:cancle];
    [alertVc addAction:walkingBtn];
    [alertVc addAction:gaodeNavigation];
    [self presentViewController:alertVc animated:YES completion:nil];
}
- (void)PGGDropView:(PGGDropView *)DropView didSelectAtIndex:(NSInteger )index{
    
    NSLog(@"%ld",index);
    NSInteger ind = index - 100;
    
    selectNumIndex = ind;
    [self.loginView.countryNumberBtn setTitle:counterNum[selectNumIndex] forState:UIControlStateNormal];
    //    cityNameLab = cityList[ind];

}
-(void)rember:(UIButton *)btn
{
    if(btn.selected == NO){
        btn.selected = YES;
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:kIsremberStr forKey:kIsremberPw];
        if (![self.loginView.userNameTf.text isEqualToString:@""]) {
            [defaults setObject:self.loginView.userNameTf.text forKey:kUserName];
        }
        if (![self.loginView.userPassWordTf.text isEqualToString:@""]) {
            [defaults setObject:self.loginView.userPassWordTf.text forKey:kUserPassWord];
        }
        [defaults synchronize];
    }
    else
    {
        btn.selected = NO;
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:kNoremberStr forKey:kIsremberPw];
        [defaults removeObjectForKey:kUserName];
        [defaults removeObjectForKey:kUserPassWord];
        [defaults synchronize];
    }
}

-(void)chang:(UIButton *)btn
{
    
    //    NSString *buttonInfo = [bundle localizedStringForKey:@"buttonInfo" value:nil table:@"hello"];if([lan isEqualToString:@"en"]){//判断当前的语言，进行改变
    
    NSString *lan = [InternationalControl userLanguage];
    if([lan isEqualToString:@"en"]){//判断当前的语言，进行改变
        [InternationalControl setUserlanguage:@"zh-Hans"];
        [self.loginView.changLau setTitle:@"English" forState:UIControlStateNormal];
    } else {
        [InternationalControl setUserlanguage:@"en"];
        [self.loginView.changLau setTitle:@"中文" forState:UIControlStateNormal];
    }
    [self changLau];
    [InternationalControl initUserLanguage];//初始化应用语言
    
//    NSBundle *bundle = [InternationalControl bundle];
//
//
//    NSString *inviteMsg = [bundle localizedStringForKey:@"log" value:nil table:@"hello"];
//    [self.loginView.loginBtn setTitle:inviteMsg forState:UIControlStateNormal];
    //改变完成之后发送通知，告诉其他页面修改完成，提示刷新界面
//    [[NSNotificationCenter defaultCenter] postNotificationName:kChangeLanguage object:nil];  
}
-(void)changLau
{
    
    
    [InternationalControl initUserLanguage];//初始化应用语言
    
    NSBundle *bundle = [InternationalControl bundle];
    
    [self.loginView.loginBtn setTitle:[bundle localizedStringForKey:@"log" value:nil table:@"hello"] forState:UIControlStateNormal];
    
    
    [self.loginView.registerBtn setTitle:[bundle localizedStringForKey:@"regis" value:nil table:@"hello"] forState:UIControlStateNormal];
    
    
     [self.loginView.forgetPWBtn setTitle:[bundle localizedStringForKey:@"forgetPW" value:nil table:@"hello"] forState:UIControlStateNormal];
    
    self.loginView.userNameTf.placeholder =[bundle localizedStringForKey:@"PhonePlaceholder" value:nil table:@"hello"];
    self.loginView.userPassWordTf.placeholder =[bundle localizedStringForKey:@"PwPlaceholder" value:nil table:@"hello"];
    
    [self.loginView.remberPwbtn setTitle:[bundle localizedStringForKey:@"checkbox" value:nil table:@"hello"] forState:UIControlStateNormal];
    
    
}
-(void)loginBtn:(UIButton *)btn
{
    //跳转首页
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    [defaults setObject:kLoginStr forKey:kIsLogin];
//    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//    [center postNotificationName:kChangeLoginNotificationName object:nil userInfo:nil];
//    return;
    
    [self refreshBegin];
    NSDictionary *dic = @{
                          @"phone":self.loginView.userNameTf.text,
                          @"password":self.loginView.userPassWordTf.text
                          };
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kFirstUrl,kLoginUrl];
    NSLog(@"urlStr:%@",urlStr);

    [DataContrller PostRequestUrl:urlStr Param:dic requestSuccess:^(NSDictionary *backDic) {
        [self refreshStop];
        
        NSLog(@"backDic:%@",backDic);
        if ([backDic[@"returnCode"] integerValue] == 200) {
            LoginModel *model = [[LoginModel alloc] initWithDictionary:backDic[@"obj"] error:nil];
            UserInfomation *user = [UserInfomation shareManager];
            user.username = model.username;
            user.phone = model.phone;
            user.pk = model.pk;
            user.rongYunToken = model.rongYunToken;
            user.picUrl = model.picUrl;
            //跳转首页
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:kLoginStr forKey:kIsLogin];
            NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
            [center postNotificationName:kChangeLoginNotificationName object:nil userInfo:nil];

            NSString *firstName = [defaults objectForKey:kIsremberPw];
            if([firstName isEqualToString:kIsremberStr])
            {
                [defaults setObject:self.loginView.userNameTf.text forKey:kUserName];
                [defaults setObject:self.loginView.userPassWordTf.text forKey:kUserPassWord];
            }
        } else {
            [self showAlert:backDic[@"msg"]];
        }
    } requestFail:^(NSString *backErrorStr) {
        [self refreshStop];
        NSLog(@"backErrorStr:%@",backErrorStr);
        [self showAlert:backErrorStr];

    }];
    
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    [defaults setObject:kLoginStr forKey:kIsLogin];
//    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//    [center postNotificationName:kChangeLoginNotificationName object:nil userInfo:nil];
    
}

-(void)forget:(UIButton *)btn
{
    RegisterViewController *registerVc = [[RegisterViewController alloc] init];
    registerVc.isForget = YES;
    [self.navigationController pushViewController:registerVc animated:YES];
}

-(void)registerBtn:(UIButton *)btn
{
    RegisterViewController *registerVc = [[RegisterViewController alloc] init];
    registerVc.isForget = NO;
    [self.navigationController pushViewController:registerVc animated:YES];
     
}

-(void)test:(UIButton *)btn
{

    
//    FirstViewController *fir = [[FirstViewController alloc] init];
//    [self.navigationController pushViewController:fir animated:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
